#include "CDGWidgetBase.h"

#include "constants.h"
#include "decoder.h"

CDGWidgetBase::CDGWidgetBase()
    : m_parsed(0),
      m_cdgFile(""),
      m_isactive(false),
      m_isplaying(false),
      m_timer(NULL),
      m_input(NULL),
      m_output(NULL),
      m_decoder(NULL)
{
}

CDGWidgetBase::~CDGWidgetBase()
{
}


bool CDGWidgetBase::isActive(void)
{
    return m_isactive;
}

void CDGWidgetBase::stopDecoder(void)
{
    if (m_decoder && m_decoder->running()) 
    {
        m_decoder->lock();
        m_decoder->stop();
        m_decoder->unlock();
    }

    if (m_decoder) 
    {
        m_decoder->lock();
        m_decoder->cond()->wakeAll();
        m_decoder->unlock();
    }

    if (m_decoder)
        m_decoder->wait();
}

void CDGWidgetBase::switchTransparency()
{
    m_cdg.switchTransparency();
}

void CDGWidgetBase::switchTransparentBkg()
{
    m_cdg.switchTransparentBkg();
}


void CDGWidgetBase::openOutputDevice(QObject *listener)
{
    QString adevice;

    if (gContext->GetSetting("MusicAudioDevice") == "default")
        adevice = gContext->GetSetting("AudioOutputDevice");
    else
        adevice = gContext->GetSetting("MusicAudioDevice");
 
    // TODO: Error checking that device is opened correctly!
    m_output = AudioOutput::OpenAudio(adevice, "default", 16, 2, 44100,
                                    AUDIOOUTPUT_MUSIC, true,
                                    false /* AC3/DTS pass through */);
    
    m_output->setBufferSize(256 * 1024);
    m_output->SetBlocking(false);
    m_output->addListener(listener);
    //Stretch
    //m_output->SetStretchFactor(0.8);

//    m_output->addListener(mainvisual);
//    m_output->addVisual(mainvisual);    
}

void CDGWidgetBase::pause(void)
{
    if (m_timer)
    {
        if (m_isplaying)
           m_timer->stop();
        else
           m_timer->start(animTimer);
    }

    if (m_output) 
       m_output->Pause(m_isplaying); //Note pause doesn't take effet instantly

    // wake up threads
    if (m_decoder) 
    {
        m_decoder->lock();
        m_decoder->cond()->wakeAll();
        m_decoder->unlock();
    }

    //Set status
    m_isplaying = !m_isplaying;
}


void CDGWidgetBase::seek(int pos)
{
    if (m_output)
    {
        m_output->Reset();
        m_output->SetTimecode(pos*1000);

        if (m_decoder && m_decoder->running()) 
        {
            m_decoder->lock();
            m_decoder->seek(pos);
            m_decoder->unlock();
        }
    }
}

void CDGWidgetBase::seekforward()
{
    int nextTime = m_output->GetAudiotime()/1000 + 5;
    cerr << "Seek: " << m_output->GetAudiotime() << "  " << nextTime << endl;
//     if (nextTime > maxTime)
//         nextTime = maxTime;
    seek(nextTime);
}

void CDGWidgetBase::seekback()
{
    int nextTime = m_output->GetAudiotime()/1000 - 5;
    if (nextTime < 0)
        nextTime = 0;
    seek(nextTime);
}

